class Solution {
public:
    int a[11];
    const int N = 10;
    void clear() {
        for (int i = 0; i < N; ++i)
            a[i] = 0;
    }
    bool istruerow(vector<char>& board) {
        for (int i = 0; i < 9; ++i) {
            if (board[i] >= '0' && board[i] <= '9')
                a[board[i] - '0']++;
        }
        for (int i = 1; i < 10; ++i) {
            if (a[i] > 1)
                return false;
        }
        return true;
    }
    bool isnine(vector<vector<char>>& board) {
        // 这里是九宫格检测 保证九宫格里不能有相同的数
        for (int i = 0; i < 9; i += 3) {
            for (int j = i; j < i + 3; ++j) {
                for (int k = 0; k < 3; ++k) {
                    if (board[j][k] >= '0' && board[j][k] <= '9')
                        a[board[j][k] - '0']++;
                }
            }
            for (int i = 1; i < 10; ++i) {
                if (a[i] > 1)
                    return false;
            }
            clear();
            for (int j = i; j < i + 3; ++j) {
                for (int k = 3; k < 6; ++k) {
                    if (board[j][k] >= '0' && board[j][k] <= '9')
                        a[board[j][k] - '0']++;
                }
            }
            for (int i = 1; i < 10; ++i) {
                if (a[i] > 1)
                    return false;
            }
            clear();
            for (int j = i; j < i + 3; ++j) {
                for (int k = 6; k < 9; ++k) {
                    if (board[j][k] >= '0' && board[j][k] <= '9')
                        a[board[j][k] - '0']++;
                }
            }
            for (int i = 1; i < 10; ++i) {
                if (a[i] > 1)
                    return false;
            }
            clear();
        }
        return true;
    }
    bool isValidSudoku(vector<vector<char>>& board) {
        // 目前光保证了行和列是可以的
        // 分为行检测和列检测 用哈希表
        for (int i = 0; i < 9; ++i) {
            // 置空
            clear();
            if (!istruerow(board[i]))
                return false; // 处理行
        }
        // 处理列
        for (int j = 0; j < 9; ++j) {
            clear();
            for (int i = 0; i < 9; ++i) {
                if (board[i][j] >= '0' && board[i][j] <= '9')
                    a[board[i][j] - '0']++;
            }
            for (int i = 1; i < 10; ++i) {
                if (a[i] > 1)
                    return false;
            }
        }
        clear();
        if (!isnine(board))
            return false;
        return true;
    }
};
